const { DataTypes } = require('sequelize');
const { sequelize } = require('../database');
const bcrypt = require('bcrypt');

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  pwd: {
    type: DataTypes.STRING,
    allowNull: false
  },
  age: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  realName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  stuNum: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  className: {
    type: DataTypes.STRING,
    allowNull: false
  }
});

// 密码加密钩子
User.beforeCreate(async (user) => {
  const salt = await bcrypt.genSalt(10);
  user.pwd = await bcrypt.hash(user.pwd, salt);
});

// 密码验证方法
User.prototype.validatePassword = async function(password) {
  return bcrypt.compare(password, this.pwd);
};

module.exports = User;